package pri.hillchen.springbootstd.bms.config.activiti;

import org.activiti.engine.*;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by hillchen on 2018/1/29.
 */
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties({
        DataSourceProperties.class
})
public class ActivitiConfiguration {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private DataSourceTransactionManager transactionManager;

    @Bean
    public SpringProcessEngineConfiguration processEngineConfiguration(){
        SpringProcessEngineConfiguration springProcessEngineConfiguration =new SpringProcessEngineConfiguration();
        springProcessEngineConfiguration.setDataSource(dataSource);
        springProcessEngineConfiguration.setTransactionManager(transactionManager);
        /*springProcessEngineConfiguration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_FALSE)
                .setJobExecutorActivate(true);*/

        springProcessEngineConfiguration.setDatabaseSchemaUpdate("create")
                .setJobExecutorActivate(true);
        return springProcessEngineConfiguration;
    }
    @Bean
    public ProcessEngine processEngine() throws Exception {
        ProcessEngineFactoryBean processEngineFactoryBean = new ProcessEngineFactoryBean();
        processEngineFactoryBean.setProcessEngineConfiguration(processEngineConfiguration());
        return processEngineFactoryBean.getObject();
    }

    @Bean
    public RepositoryService repositoryService() throws Exception {
        return  processEngine().getRepositoryService();
    }

    @Bean
    public RuntimeService runtimeService() throws Exception {
        return  processEngine().getRuntimeService();
    }

    @Bean
    public TaskService taskService() throws Exception {
        return  processEngine().getTaskService();
    }

    @Bean
    public HistoryService historyService() throws Exception {
        return  processEngine().getHistoryService();
    }

    @Bean
    public ManagementService managementService() throws Exception {
        return  processEngine().getManagementService();
    }
}
